package com.example.mydemo;

import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mydemo.utils.FileUtil;
import com.github.gzuliyujiang.filepicker.ExplorerConfig;
import com.github.gzuliyujiang.filepicker.FilePicker;
import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode;
import com.github.gzuliyujiang.filepicker.contract.OnFilePickedListener;
import com.google.gson.Gson;
import com.tal.pad.eye_protection.AwConDetectApi;
import com.tal.pad.eye_protection.ResultInfo;
import com.tal.pad.eye_protection.interfaces.NoPersonStatusCallback;
import com.tal.pad.eye_protection.interfaces.ProtectEyeResultCallback;
import com.tal.pad.eye_protection.util.AssetsUtil;
import com.tal.pad.eye_protection.util.VideoUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class VideoTestActivity extends AppCompatActivity implements OnFilePickedListener {
    private TextView tv_result;
    private TextView tv_log;
    private TextView tv_name;
    private VideoView videoView;
    private static final int MSG_GET_RESULT = 102;
    private static final int MSG_SET_RESULT = 103;
    private static final long TIME_WORK=5000;

    private List<File> listFile ;
    private boolean isStartCanClick=false;
    private int curentPlayNum=0;

    private StringBuffer buffer=new StringBuffer();
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            
                case MSG_GET_RESULT:
                    AwConDetectApi.getInstance().getResult(new ProtectEyeResultCallback() {
                        @Override
                        public void onResult(ResultInfo resultInfo) {
                            Message msg0 = Message.obtain();
                            msg0.what = MSG_SET_RESULT;
                            msg0.obj = resultInfo;
                            sendMessage(msg0);
                        }
                    });

                    break;
                case MSG_SET_RESULT:
                    ResultInfo reBean = (ResultInfo) msg.obj;
                    String str = "趴着次数:" + reBean.prostrate_time + " 打哈欠次数:" + reBean.yawn_count +
                            " 瞌睡次数:" + reBean.sleep_time + " 低头次数:" + reBean.headdown_time +
                            " 俯视次数:" + reBean.lookdown_time + " 仰头次数:" + reBean.headup_time +
                            " 抬头次数:" + reBean.lookup_time + " 歪头次数:" + reBean.headtilt +
                            " 侧脸次数:" + reBean.faceprofile + " 东张西望次数:" + reBean.lookaround +
                            " 斜肩次数:" + reBean.shouldertilt;
                    tv_result.setText("结果：\n" + str);

                    Date currentDate = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    String formattedDate = dateFormat.format(currentDate);
                    Log.e("++ Mr.Zan ++", "handleMessage: "+ curentPlayNum);
                    String name ="\n"+formattedDate+"\n 文件名称："+ listFile.get(curentPlayNum-1).getName();
                    buffer.append(name+"\n"+new Gson().toJson(reBean));
                    FileUtil.writeToTxt(name+"\n"+new Gson().toJson(reBean));
                    tv_log.setText(buffer);

                    break;

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_test);
        videoView=findViewById(R.id.videoView);
        tv_result=findViewById(R.id.tv_result);
        tv_log=findViewById(R.id.tv_log);
        tv_name=findViewById(R.id.tv_select_name);
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                curentPlayNum++;
                if (curentPlayNum<=listFile.size()){
                    handler.sendEmptyMessage(MSG_GET_RESULT);
                }
                if (curentPlayNum<listFile.size()){
                    detectVideo(listFile.get(curentPlayNum));
                }
            }
        });
    }

    public void selectVideo(View view){
        ExplorerConfig config = new ExplorerConfig(this);
        config.setRootDir(Environment.getExternalStorageDirectory());
        config.setLoadAsync(false);
        config.setExplorerMode(ExplorerMode.DIRECTORY);
        config.setOnFilePickedListener(this);
//        config.setAllowExtensions(new String[]{".mp4"});
        FilePicker picker = new FilePicker(this);
        picker.setExplorerConfig(config);
        picker.show();
    }
    public void startVideo(View view){
        if (isStartCanClick){
            isStartCanClick=false;
            curentPlayNum=0;
            detectVideo(listFile.get(curentPlayNum));
        }
    }
    public void getResult(View view) {
        AwConDetectApi.getInstance().getResult(resultInfo -> {

            handler.post(() -> tv_result.setText("结果：" + new Gson().toJson(resultInfo)));
        });
    }
    public void resetResult(View view) {
        tv_result.setText("");
        AwConDetectApi.getInstance().resetResult();
    }

    public void clearLog(View view) {
        buffer.setLength(0);
        tv_log.setText("");
    }
    public void getNoPersonStatus(View view){
        AwConDetectApi.getInstance().getNoPersonStatus(new NoPersonStatusCallback() {
            @Override
            public void onNoPersonStatus(int status) {
                Log.e("+++", "onNoPersonStatus: "+status );
            }
        });
    }

    @Override
    public void onFilePicked(@NonNull File file) {
        Log.e("++ Mr.Zan ++", "onFilePicked: "+file.getPath() );
        if (listFile==null){
            listFile =new ArrayList<>();
        }else {
            listFile.clear();
        }
        isStartCanClick=true;
        listFile.addAll(FileUtil.getMp4Files(file.getPath()));
        String videoName="已选文件名称：\n";
        for (int i = 0; i < listFile.size(); i++) {
            videoName+=listFile.get(i).getName()+"\n";
        }
        tv_name.setText(videoName);
    }
    public void detectVideo(File file){
        VideoUtils.getInstance().init(this, videoView, Uri.fromFile(file), new VideoUtils.OnFrameCapturedListener() {
            @Override
            public void onFrameCaptured(Bitmap bitmap) {
                if (bitmap==null){
                    return;
                }
                byte[] data= AssetsUtil.convertBitmapToNV21(bitmap);
//                FileUtils2.getInstance().processFrame(data,bitmap.getWidth(), bitmap.getHeight(), ImageFormat.NV21,"NV21");
                AwConDetectApi.getInstance().detectFrame(data, bitmap.getWidth(), bitmap.getHeight(), 0, 0, 1, file.getName());

            }
        });
    }
}